/**
 * @file util.c
 * @brief Utility functions
 * @author Scott Moyers
 * @date 2009
 */

#include "util.h"
#include <stdio.h>

int number_of_set_bits(int i)
{
	i = i - ((i >> 1) & 0x55555555);
	i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
	return (((i + (i >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}

void to_binary(char *buf, int val, int bits)
{
	int i;
	buf[bits] = '\0';
	for(i = 1; i <= bits; i++) {
		buf[bits - i] = GET_BIT(i - 1, val) | 0x30;
	}
}

void swap(int *a, int *b)
{
	if (*a != *b) {
		int tmp = *b;
		*b = *a;
		*a = tmp;
	}
}

unsigned int sum_of_1_n(unsigned int n)
{
	return ((n + 1) * n) / 2;
}

void *smalloc(size_t s)
{
	void *p = malloc(s);
	if (p == NULL) {
		fprintf(stderr,
			"Error: malloc failed, could not allocate %lu bytes",
			(unsigned long) s);
		exit(1);
	}
	return p;
}

void *scalloc(size_t e, size_t s)
{
	void *p = calloc(e, s);
	if (p == NULL) {
		fprintf(stderr,
			"Error: calloc failed, could not allocate %lu bytes",
			(unsigned long) s);
		exit(1);
	}
	return p;
}
